package com.topdt.jbpm.form;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Entities;
import org.jsoup.select.Elements;

import com.thx.common.spring.BeanFactory;
import com.thx.common.util.AppContext;
import com.thx.common.util.ThreadLocalContext;
import com.topdt.jbpm.Constants;
import com.topdt.jbpm.form.query.Option;
import com.topdt.jbpm.model.Activity;
import com.topdt.jbpm.model.Field;
import com.topdt.jbpm.model.Form;
import com.topdt.jbpm.service.CommentService;
import com.topdt.jbpm.service.FieldService;
import com.topdt.jbpm.utils.FreeMakerUtils;
import com.topdt.jbpm.utils.TreeUtils;

import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 *
 * 建立日期 : 2013-5-31 下午02:34:18<br>
 * 作者 : shiyan<br>
 * 模块 : <br>
 * 描述 : <br>
 * 修改历史: 序号 日期 修改人 修改原因 <br>
 * 1 <br>
 * 2 <br>
 */
public class TemplateCreater {

	private static final String ROW_FORMAT = "<tr><td>%s</td></tr>";
	public static final String FILED_FORMAT = "<div class=\"item\" %s><div class=\"item-label\"><label>%s</label></div><div class=\"item-data\">%s</div></div>";
	// --s 分别为class 校验 字段名称 字段名称 字段默认值
//	private static final String TEXT_FORMAT = "<input class=\"%s\" %s type=\"text\" name=\"%s\"  value=\"${%s.value!'%s'}\" style=\"width:284px;height:25px\"/>";
	private static final String TEXT_FORMAT = "<input class=\"form-control %s\" %s type=\"text\" name=\"%s\"  value=\"${%s.value!'%s'}\" />";
	// --s 分别为 class 校验 字段名称 字段名称 字段默认值
//	private static final String TEXTAREA_FORMAT = "<textarea class=\"more easyui-validatebox %s\" %s name=\"%s\" style=\"height:300px;width:711px\">${%s.value!'%s'}</textarea>";
	private static final String TEXTAREA_FORMAT = "<textarea class=\"form-control %s\" %s name=\"%s\" style=\"height:300px;\">${%s.value!'%s'}</textarea>";
	// --s 分别为 校验 字段名称 optionValue OptionName
//	private static final String RADIO_FORMAT = "<input class=\"easyui-validatebox %s\" %s type=\"radio\" name=\"%s\" value=\"%s\"  style=\"height:25px\"/><span>%s</span>";
	private static final String RADIO_FORMAT = "<input class=\"%s\" type=\"radio\" name=\"%s\" value=\"%s\" /><span>%s</span>";
	// --s 分别为 校验 字段名称 optionValue OptionName
//	private static final String CHECKBOX_FORMAT = "<input class=\"easyui-validatebox %s\" %s type=\"checkbox\" name=\"%s\" value=\"%s\" style=\"height:25px\"/><span>%s</span>";
	private static final String CHECKBOX_FORMAT = "<input class=\"%s\" %s type=\"checkbox\" name=\"%s\" value=\"%s\" /><span>%s</span>";
	// --s 分别为class 校验 字段名称 options
//	private static final String SELECT_FORMAT = "<select class=\"easyui-validatebox %s\" %s name=\"%s\" style=\"width:284px;height:25px\">%s</select>";
	private static final String SELECT_FORMAT = "<select class=\"form-control %s\" %s name=\"%s\" >%s</select>";
	// --optionValue OptionName
	private static final String OPTION_FORMAT = "<option value=\"%s\">%s</option>";
	// --s 分别为 校验 字段名称 字段名称 字段默认值 id=\"%s\"
	private static final String RICHTEXT_FORMAT = "<textarea class=\"more easyui-validatebox richText %s\"  %s  name=\"%s\" >${%s.value!'%s'}</textarea>";
	// -- s 分别为 校验 json文件 字段名称 字段名称 字段默认值
	private static final String TREE_FORMAT = "<input class=\"easyui-combotree %s\" %s data-options=\"url:'%s'\" type=\"text\" name=\"%s\"  value=\"${%s.value!'%s'}\" style=\"height:25px\"/>";
	// --s 分别为字段名称 字段名称 默认值
	private static final String HIDDEN_FORMAT = "<input type=\"hidden\" id=\"%sValue\" value=\"${%s.value!'%s'}\"/>";
	// --s 分别为校验 optionValue
//	private static final String SYSVAR_FORMAT = "<input type=\"text\"  %s name=\"%s\" value=\"${%s.value!'%s'}\" readonly=\"readonly\" />";
	private static final String SYSVAR_FORMAT = "<input class=\"form-control\" type=\"text\" name=\"%s\" value=\"${%s.value!'%s'}\" readonly=\"readonly\" />";
	private static final String MISSINGMESSAGE = "missingMessage=\"%s不可以为空！\"";
	private static final String DISPLAY = "style=\"${%s.show!''}\"";
	private static final String READONLY = "${%s.readonly!''}";
	private static final String VALIDATTYPE = "data-options=\"validType:'%s'\"";
	private static final String INVALIDMESSAGE = "invalidMessage=\"%s\"";

	private static final String FILED_FORMAT_M = "<div data-role=\"fieldcontain\" %s > <label >%s</label>  %s </div>";
	private static final String INPUT_FORMAT_M = "<input data-mini=\"true\" name=\"%s\" value=\"${%s.value!'%s'}\" class=\"%s\"  type=\"%s\" data-mini=\"true\" %s/>";
	private static final String SELECT_FORMAT_M = "<select data-mini=\"true\" class=\"%s\" name=\"%s\" >%s</select>";
	private static final String OPTION_FORMAT_M = "<option  value=\"%s\">%s</option>";
	private static final String HIDDEN_FORMAT_M = "<input type=\"hidden\" id=\"%sValue\" value=\"${%s.value!'%s'}\"/>";
	private static final String CHECKBOX_FORMAT_M = "<input data-mini=\"true\" class=\"%s\" id=\"%s\" type=\"checkbox\" name=\"%s\" value=\"%s\" /><label for=\"%s\">%s</label>";
	private static final String SYSVAR_FORMAT_M = "<input data-mini=\"true\" type=\"text\"  %s name=\"%s\" value=\"${%s.value!'%s'}\" readonly=\"readonly\" />";
	private static final String TEXTAREA_FORMAT_M = "<textarea data-mini=\"true\" class=\"more %s\" name=\"%s\" %s>${%s.value!'%s'}</textarea>";
	private static final String CHECK_FORMAT_M = "<div data-role=\"fieldcontain\" %s > <fieldset data-role=\"controlgroup\" data-mini=\"true\" data-type=\"vertical\"><label>%s</label> %s </fieldset></div>";
	private static final String RADIO_FORMAT_M = "<input data-mini=\"true\" class=\"%s\" id=\"%s\" type=\"radio\" name=\"%s\" value=\"%s\" /><label for=\"%s\">%s</label>";

	private static final String FORM_FORMAT = "<form id=\"form-Tem\"><input type=\"hidden\" name=\"appId\" value=\"${appId!''}\" /><input type=\"hidden\" id=\"workId\" name=\"workId\" value=\"${workId!''}\" /><table>%s</table>";
	private static SysParamService sysParamService = (SysParamService) BeanFactory.getBean(SysParamService.class);

	public static String getFormHtml(Form form) {
		List<Field> fields = new ArrayList<Field>();
		FieldService fieldService = (FieldService) BeanFactory.getBean("fieldService");
		fields = fieldService.getFieldsByformId(form.getFormId());

		StringBuilder rows = new StringBuilder();
		for (Field field : fields) {
			String fieldDiv = getFieldDiv(field);
			rows.append(String.format(ROW_FORMAT, fieldDiv));
		}

		return String.format(FORM_FORMAT, rows.toString());

	}

	public static List<String> listFieldHtml(Form form) {
		List<String> fieldDivs = new ArrayList<String>();
		List<Field> fields = new ArrayList<Field>();
		FieldService fieldService = (FieldService) BeanFactory.getBean("fieldService");
		fields = fieldService.getShowFieldsByformId(form.getFormId());
		for (Field field : fields) {
			String fieldDiv = getFieldDiv(field);
			fieldDivs.add(fieldDiv);
		}
		return fieldDivs;
	}

	public static String createTemplate(String tableHtml) {
		/*
		 * String contextPath =
		 * ServletActionContext.getServletContext().getRealPath
		 * (java.io.File.separator); if(StringUtils.isBlank(contextPath)){
		 * contextPath =
		 * ServletActionContext.getServletContext().getRealPath("/"); }
		 */
		String contextPath = null;// TODO 调整
		String temPath = contextPath + java.io.File.separator + AppContext.getProperties("formTemplatePath");
		File folder = new File(temPath);
		File temp = new File(folder, "form.template");
		if (!temp.exists())
			return "系统模板不存在！";
		String tempString = "";
		try {
			Document doc = Jsoup.parse(temp, "UTF-8", "");
			Element div = doc.getElementById("form-Tem");
			div.append(tableHtml);
			tempString = doc.html();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return tempString;
	}

	/**
	 *
	 * 建立日期 : 2013-10-16 下午4:18:34<br>
	 * 作者 : 石艳<br>
	 * 描述 : 获取表单字段表格html片段的方法<br>
	 */
	public static String getTableHtmlByForm(Form form) {
		Document doc = null;
		if (form.getTempletStorageType() != null && !"".equals(form.getTempletStorageType())
				&& "byte".equals(form.getTempletStorageType())) {
			try {
				String template = new String(form.getTempletByte(), "UTF-8");
				doc = Jsoup.parse(template, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else if ("file".equals(form.getTempletStorageType())) {
			/*
			 * String contextPath =
			 * ServletActionContext.getServletContext().getRealPath
			 * (java.io.File.separator); if(StringUtils.isBlank(contextPath)){
			 * contextPath =
			 * ServletActionContext.getServletContext().getRealPath("/"); }
			 */

			String contextPath = null;// TODO 调整
			String temPath = contextPath + java.io.File.separator + AppContext.getProperties("formTemplatePath");
			File folder = new File(temPath);
			File file = new File(folder, form.getTempletPath());
			if (!file.exists())
				return "表单模板不存在或路径错误！";
			try {
				doc = Jsoup.parse(file, "UTF-8", "");
			} catch (IOException e) {
				e.printStackTrace();
				return "表单模板不存在或路径错误！";
			}
		}
		Element div = doc.getElementById("form-Tem");
		Element table = div.getElementsByTag("table").first();
		return "<table  style=\"width:100%;\" cellpadding=\"2\" cellspacing=\"0\" border=\"1\" bordercolor=\"#000000\">"
				+ table.html() + "</table>";
	}

	@SuppressWarnings("unchecked")
	public static String getTemplate(Form form) {

		// --先得到系统默认的模板
		/*
		 * String contextPath =
		 * ServletActionContext.getServletContext().getRealPath
		 * (java.io.File.separator); if(StringUtils.isBlank(contextPath)){
		 * contextPath =
		 * ServletActionContext.getServletContext().getRealPath("/"); }
		 */

		String contextPath = null;// TODO 需要调整一下
		String temPath = contextPath + java.io.File.separator + AppContext.getProperties("formTemplatePath");
		File folder = new File(temPath);
		File temp = new File(folder, "form.template");
		if (!temp.exists())
			return "系统模板不存在！";

		File file = new File(folder, "tem.ftl");

		try {
			if (!file.exists()) {
				file.createNewFile();
			}
			Document doc = Jsoup.parse(temp, "UTF-8", "");
			Element div = doc.getElementById("formContent");

			String formHtml = getFormHtml(form);

			div.html(formHtml);
			String tempString = doc.html();
			BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
			out.write(tempString, 0, tempString.length());
			out.close();
		} catch (IOException e1) {
			e1.printStackTrace();
		}

		Template template = null;
		try {
			template = FreeMakerUtils.getTemplate(file.getName(),"");//TODO 调整路径
		} catch (IOException e) {
			e.printStackTrace();
		}

		// --整合数据 字段权限数据和操作数据
		Map root = new HashMap();
		FieldService fieldService = (FieldService) BeanFactory.getBean("fieldService");
		List<Field> fields = fieldService.getFieldsByformId(form.getFormId());
		if (fields != null && fields.size() > 0) {
			for (Field field : fields) {
				String fieldName = field.getFieldName();
				Map att = new HashMap();
				root.put(fieldName, att);
				if ("systemVar".equals(field.getFieldType())) {
					root.put(field.getFieldOption(), SystemVarEval.getValue(field.getFieldOption()));
				}
			}
		}
		HttpServletRequest request = (HttpServletRequest) ThreadLocalContext.get(Constants.CONTEXT_HTTPREQ);
		String path = request.getContextPath();
		root.put("path", path);
		Writer out = new StringWriter();
		try {
			template.process(root, out);
		} catch (TemplateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return out.toString();
	}

	/**
	 * 客户端字段HTMl片段生成方法 建立日期 : Aug 20, 2013 3:26:05 PM<br>
	 * 作者: 孙耀飞<br>
	 * 模块: <br>
	 * 描述: <br>
	 * 1 <br>
	 * 2 <br>
	 */
	public static String getFieldDivM(Field field) {
		String fieldName = field.getFieldName();
		String fieldText = field.getFieldText() + ":";
		if (field.getFieldType().equals("text") || field.getFieldType().equals("url")
				|| field.getFieldType().equals("number") || field.getFieldType().equals("email")
				|| field.getFieldType().equals("time") || field.getFieldType().equals("date")
				|| field.getFieldType().equals("datetime") || field.getFieldType().equals("mobile")
				|| field.getFieldType().equals("phone") || field.getFieldType().equals("tree")) {
			String clazz = String.format(READONLY, fieldName) + " ";
			if ("Y".equals(field.getIsNecessary()))
				clazz += "required ";

			String validate = "";
			if (field.getFieldLength() != null) {
				validate += "maxlength=\"" + field.getFieldLength() + "\" ";
			}

			String filedType = field.getFieldType();
			if (field.getFieldType().equals("mobile")) {
				validate += "isMobile=\"true\" ";
				filedType = "text";
			}
			if (field.getFieldType().equals("phone")) {
				validate += "isTel=\"true\" ";
				filedType = "text";
			}
			if (field.getFieldType().equals("tree")) {
				filedType = "text";
			}

			String defaultValue = "";
			if (field.getDefaultValue() != null && !"".equals(field.getDefaultValue()))
				defaultValue = field.getDefaultValue();

			String input = String.format(INPUT_FORMAT_M, fieldName, fieldName, defaultValue, clazz, filedType, validate);

			String display = "";
			if (field.getIsShow() != null && "N".equals(field.getIsShow())) {
				display += "style=\"display:none\"" + " ";
			} else {
				display += String.format(DISPLAY, fieldName) + " ";
			}
			String div = String.format(FILED_FORMAT_M, display, fieldText, input);
			return div;
		} else if (field.getFieldType().equals("select")) {
			String clazz = String.format(READONLY, fieldName) + " ";

			if ("Y".equals(field.getIsNecessary()))
				clazz += " required ";

			String defaultValue = "";
			if (field.getDefaultValue() != null && !"".equals(field.getDefaultValue()))
				defaultValue = field.getDefaultValue();
			String input = String.format(HIDDEN_FORMAT_M, fieldName, fieldName, defaultValue);

			List<Option> options = sysParamService.getOptions(field.getFieldOption(), FieldTypeDefin.getFiledTypeByKey(field.getFieldType()).getParam());
			String ops = "";
			for (Option option : options) {
				ops += String.format(OPTION_FORMAT_M, option.getId(), option.getName());
			}
			input += String.format(SELECT_FORMAT_M, clazz, fieldName, ops);

			String display = "";
			if (field.getIsShow() != null && "N".equals(field.getIsShow())) {
				display += "style=\"display:none\"" + " ";
			} else {
				display += String.format(DISPLAY, fieldName) + " ";
			}
			String div = String.format(FILED_FORMAT_M, display, fieldText, input);

			return div;
		} else if (field.getFieldType().equals("radio")) {
			String clazz = String.format(READONLY, fieldName) + " ";

			if ("Y".equals(field.getIsNecessary()))
				clazz += "required" + " ";

			String defaultValue = "";
			if (field.getDefaultValue() != null && !"".equals(field.getDefaultValue()))
				defaultValue = field.getDefaultValue();

			String input = String.format(HIDDEN_FORMAT_M, fieldName, fieldName, defaultValue);
			List<Option> options = sysParamService.getOptions(field.getFieldOption(), FieldTypeDefin.getFiledTypeByKey(field.getFieldType()).getParam());
			for (Option option : options) {
				String radioId = "radio" + new Date().getTime() + new Random();
				input += String.format(RADIO_FORMAT_M, clazz, radioId, fieldName, option.getId(), radioId, option.getName());
			}
			String display = "";
			if (field.getIsShow() != null && "N".equals(field.getIsShow())) {
				display += "style=\"display:none\"" + " ";
			} else {
				display += String.format(DISPLAY, fieldName) + " ";
			}

			String div = String.format(CHECK_FORMAT_M, display, fieldText, input);

			return div;
		} else if (field.getFieldType().equals("checkbox")) {
			String clazz = String.format(READONLY, fieldName) + " ";

			if ("Y".equals(field.getIsNecessary()))
				clazz += "required" + " ";

			String defaultValue = "";
			if (field.getDefaultValue() != null && !"".equals(field.getDefaultValue()))
				defaultValue = field.getDefaultValue();

			String input = String.format(HIDDEN_FORMAT_M, fieldName, fieldName, defaultValue);
			List<Option> options = sysParamService.getOptions(field.getFieldOption(), FieldTypeDefin.getFiledTypeByKey(field.getFieldType()).getParam());
			for (Option option : options) {
				String checkboxId = "checkbox" + new Date().getTime() + new Random();
				input += String.format(CHECKBOX_FORMAT_M, clazz, checkboxId, fieldName, option.getId(), checkboxId, option.getName());
			}

			String display = "";
			if (field.getIsShow() != null && "N".equals(field.getIsShow())) {
				display += "style=\"display:none\"" + " ";
			} else {
				display += String.format(DISPLAY, fieldName) + " ";
			}
			String div = String.format(CHECK_FORMAT_M, display, fieldText, input);

			return div;
		} else if (field.getFieldType().equals("systemVar")) {
			String validate = "style=\"border:0;background:transparent;box-shadow:none;\"" + " ";
			String input = "";
			List<Option> options = sysParamService.getOptions(field.getFieldOption(), FieldTypeDefin.getFiledTypeByKey(field.getFieldType()).getParam());
			// --一般options的size 为1 optionName 和optionValue 可能相同
			// 例如当前用户这个系统变量，optionName和optionValue可以都为表达式
			for (Option option : options) {
				input += String.format(SYSVAR_FORMAT_M, validate, fieldName, fieldName, "${" + option.getValue() + "}");
			}
			String display = "";
			if (field.getIsShow() != null && "N".equals(field.getIsShow())) {
				display += "style=\"display:none\"" + " ";
			} else {
				display += String.format(DISPLAY, fieldName) + " ";
			}
			String result = String.format(FILED_FORMAT_M, display, fieldText, input);

			return result;

		} else if (field.getFieldType().equals("richTextEditer") || field.getFieldType().equals("textarea")) {
			String clazz = String.format(READONLY, fieldName) + " ";

			if ("Y".equals(field.getIsNecessary()))
				clazz += "required" + " ";

			String validate = "";
			if (field.getFieldLength() != null) {
				validate += "maxlength=\"" + field.getFieldLength() + "\" ";
			}
			String defaultValue = "";
			if (field.getDefaultValue() != null && !"".equals(field.getDefaultValue()))
				defaultValue = field.getDefaultValue();

			String input = String.format(TEXTAREA_FORMAT_M, clazz, fieldName, validate, fieldName, defaultValue);
			String display = "";
			if (field.getIsShow() != null && "N".equals(field.getIsShow())) {
				display += "style=\"display:none\"" + " ";
			} else {
				display += String.format(DISPLAY, fieldName) + " ";
			}
			String result = String.format(FILED_FORMAT_M, display, fieldText, input);

			return result;
		}
		return "";
	}

	/**
	 *
	 * 建立日期 : 2013-10-16 下午3:59:15<br>
	 * 作者 : 石艳<br>
	 * 描述 : 表单字段html片段生成方法<br>
	 */
	public static String getFieldDiv(Field field) {
		String fieldName = field.getFieldName();
		String fieldText = field.getFieldText();
		if ("text".equals(field.getFieldType())) {
//			String clazz = "easyui-validatebox" + " ";
			String clazz = String.format(READONLY, fieldName) + " ";

			String validate = "";
			if ("Y".equals(field.getIsNecessary()))
//				validate += "required=\"true\"" + " " + String.format(MISSINGMESSAGE, fieldText) + " ";
				validate += "required=\"true\"" + " ";

			if (field.getFieldLength() != null) {
//				String validatType = "length[0," + field.getFieldLength().intValue() + "]";
//				String invalidMessage = "长度不能大于" + field.getFieldLength().intValue() + "！";
//				validate += String.format(VALIDATTYPE, validatType) + " ";
//				validate += String.format(INVALIDMESSAGE, invalidMessage) + " ";
				validate += "maxlength=\"" + field.getFieldLength().intValue() + "\"";
			}
			String defaultValue = "";
			if (field.getDefaultValue() != null && !"".equals(field.getDefaultValue()))
				defaultValue = field.getDefaultValue();

			String input = String.format(TEXT_FORMAT, clazz, validate, fieldName, fieldName, defaultValue);

			String display = "";
			if (field.getIsShow() != null && "N".equals(field.getIsShow())) {
				display += "style=\"display:none\"" + " ";
			} else {
				display += String.format(DISPLAY, fieldName) + " ";
			}

			String result = String.format(FILED_FORMAT, display, fieldText, input);

			return result;
		} else if ("textarea".equals(field.getFieldType())) {
			String clazz = String.format(READONLY, fieldName) + " ";
			String validate = "";
			if ("Y".equals(field.getIsNecessary()))
				validate += "required=\"true\"" + " ";

			if (field.getFieldLength() != null) {
//				String validatType = "length[0," + field.getFieldLength().intValue() + "]";
//				String invalidMessage = "长度不能大于" + field.getFieldLength().intValue() + "！";
//				validate += String.format(VALIDATTYPE, validatType) + " ";
//				validate += String.format(INVALIDMESSAGE, invalidMessage) + " ";
				validate += "maxlength=\"" + field.getFieldLength().intValue() + "\"";
			}

			String defaultValue = "";
			if (field.getDefaultValue() != null && !"".equals(field.getDefaultValue()))
				defaultValue = field.getDefaultValue();

			String input = String.format(TEXTAREA_FORMAT, clazz, validate, fieldName, fieldName, defaultValue);

			String display = "";
			if (field.getIsShow() != null && "N".equals(field.getIsShow())) {
				display += "style=\"display:none\"" + " ";
			} else {
				display += String.format(DISPLAY, fieldName) + " ";
			}

			String result = String.format(FILED_FORMAT, display, fieldText, input);

			return result;
		} else if ("number".equals(field.getFieldType())) {
//			String clazz = "easyui-numberbox" + " ";
			String clazz = String.format(READONLY, fieldName) + " ";

			String validate = "number=\"true\"" + " ";

			if ("Y".equals(field.getIsNecessary()))
//				validate += "required=\"true\"" + " " + String.format(MISSINGMESSAGE, fieldText) + " ";
				validate += "required=\"true\"" + " ";

			if (field.getFieldLength() != null) {
//				String validatType = "length[0," + field.getFieldLength().intValue() + "]";
//				String invalidMessage = "长度不能大于" + field.getFieldLength().intValue() + "！";
//				validate += String.format(VALIDATTYPE, validatType) + " ";
//				validate += String.format(INVALIDMESSAGE, invalidMessage) + " ";
				validate += "max=\"" + field.getFieldLength().intValue() + "\"";
			}

			String defaultValue = "";
			if (field.getDefaultValue() != null && !"".equals(field.getDefaultValue()))
				defaultValue = field.getDefaultValue();

			String input = String.format(TEXT_FORMAT, clazz, validate, fieldName, fieldName, defaultValue);

			String display = "";
			if (field.getIsShow() != null && "N".equals(field.getIsShow())) {
				display += "style=\"display:none\"" + " ";
			} else {
				display += String.format(DISPLAY, fieldName) + " ";
			}
			String result = String.format(FILED_FORMAT, display, fieldText, input);
			return result;
		} else if ("email".equals(field.getFieldType())) {
//			String clazz = "easyui-validatebox" + " ";
			String clazz = String.format(READONLY, fieldName) + " ";

			String validate = "email=\"true\"" + " ";

			if ("Y".equals(field.getIsNecessary()))
//				validate += "required=\"true\"" + " " + String.format(MISSINGMESSAGE, fieldText) + " ";
				validate += "required=\"true\"" + " ";
//			String validatType = "email";
//			String invalidMessage = " 请输入正确的邮箱地址!";
//			validate += String.format(VALIDATTYPE, validatType) + " ";
//			validate += String.format(INVALIDMESSAGE, invalidMessage) + " ";

			String defaultValue = "";
			if (field.getDefaultValue() != null && !"".equals(field.getDefaultValue()))
				defaultValue = field.getDefaultValue();

			String input = String.format(TEXT_FORMAT, clazz, validate, fieldName, fieldName, defaultValue);

			String display = "";
			if (field.getIsShow() != null && "N".equals(field.getIsShow())) {
				display += "style=\"display:none\"" + " ";
			} else {
				display += String.format(DISPLAY, fieldName) + " ";
			}
			String result = String.format(FILED_FORMAT, display, fieldText, input);

			return result;
		} else if ("date".equals(field.getFieldType())) {
//			String clazz = "easyui-datebox" + " ";
			String clazz = "config-date" + " ";
			clazz += String.format(READONLY, fieldName) + " ";

			String validate = "readonly=\"readonly\"" + " ";

			if ("Y".equals(field.getIsNecessary()))
//				validate += "required=\"true\"" + " " + String.format(MISSINGMESSAGE, fieldText) + " ";
				validate += "required=\"true\"" + " ";

			String defaultValue = "";
			if (field.getDefaultValue() != null && !"".equals(field.getDefaultValue()))
				defaultValue = field.getDefaultValue();

			String input = String.format(TEXT_FORMAT, clazz, validate, fieldName, fieldName, defaultValue);

			String display = "";
			if (field.getIsShow() != null && "N".equals(field.getIsShow())) {
				display += "style=\"display:none\"" + " ";
			} else {
				display += String.format(DISPLAY, fieldName) + " ";
			}
			String result = String.format(FILED_FORMAT, display, fieldText, input);

			return result;

		} else if ("datetime".equals(field.getFieldType())) {
			String clazz = "easyui-datetimebox" + " ";
			clazz += String.format(READONLY, fieldName) + " ";

			String validate = "";

			if ("Y".equals(field.getIsNecessary()))
				validate += "required=\"true\"" + " " + String.format(MISSINGMESSAGE, fieldText) + " ";

			String defaultValue = "";
			if (field.getDefaultValue() != null && !"".equals(field.getDefaultValue()))
				defaultValue = field.getDefaultValue();

			String input = String.format(TEXT_FORMAT, clazz, validate, fieldName, fieldName, defaultValue);

			String display = "";
			if (field.getIsShow() != null && "N".equals(field.getIsShow())) {
				display += "style=\"display:none\"" + " ";
			} else {
				display += String.format(DISPLAY, fieldName) + " ";
			}
			String result = String.format(FILED_FORMAT, display, fieldText, input);

			return result;
		} else if ("time".equals(field.getFieldType())) {
			String clazz = "easyui-timespinner" + " ";
			clazz += String.format(READONLY, fieldName) + " ";

			String validate = "";

			if ("Y".equals(field.getIsNecessary()))
				validate += "required=\"true\"" + " " + String.format(MISSINGMESSAGE, fieldText) + " ";

			String defaultValue = "";
			if (field.getDefaultValue() != null && !"".equals(field.getDefaultValue())) {
				defaultValue = field.getDefaultValue();
			} else {
				defaultValue = "00:00";
			}

			String input = String.format(TEXT_FORMAT, clazz, validate, fieldName, fieldName, defaultValue);

			String display = "";
			if (field.getIsShow() != null && "N".equals(field.getIsShow())) {
				display += "style=\"display:none\"" + " ";
			} else {
				display += String.format(DISPLAY, fieldName) + " ";
			}
			String result = String.format(FILED_FORMAT, display, fieldText, input);

			return result;
		} else if ("mobile".equals(field.getFieldType())) {

//			String clazz = "easyui-validatebox" + " ";
			String clazz = String.format(READONLY, fieldName) + " ";

			String validate = "isMobile=\"true\"" + " ";

			if ("Y".equals(field.getIsNecessary()))
//				validate += "required=\"true\"" + " " + String.format(MISSINGMESSAGE, fieldText) + " ";
				validate += "required=\"true\"" + " ";

//			String validatType = "mobile";
//			validate += String.format(VALIDATTYPE, validatType) + " ";

			String defaultValue = "";
			if (field.getDefaultValue() != null && !"".equals(field.getDefaultValue()))
				defaultValue = field.getDefaultValue();

			String input = String.format(TEXT_FORMAT, clazz, validate, fieldName, fieldName, defaultValue);

			String display = "";
			if (field.getIsShow() != null && "N".equals(field.getIsShow())) {
				display += "style=\"display:none\"" + " ";
			} else {
				display += String.format(DISPLAY, fieldName) + " ";
			}
			String result = String.format(FILED_FORMAT, display, fieldText, input);

			return result;
		} else if ("phone".equals(field.getFieldType())) {
//			String clazz = "easyui-validatebox" + " ";
			String clazz = String.format(READONLY, fieldName) + " ";

			String validate = "isTel=\"true\"" + " ";

			if ("Y".equals(field.getIsNecessary()))
//				validate += "required=\"true\"" + " " + String.format(MISSINGMESSAGE, fieldText) + " ";
				validate += "required=\"true\"" + " ";

//			String validatType = "phone";
//			validate += String.format(VALIDATTYPE, validatType) + " ";

			String defaultValue = "";
			if (field.getDefaultValue() != null && !"".equals(field.getDefaultValue()))
				defaultValue = field.getDefaultValue();

			String input = String.format(TEXT_FORMAT, clazz, validate, fieldName, fieldName, defaultValue);

			String display = "";
			if (field.getIsShow() != null && "N".equals(field.getIsShow())) {
				display += "style=\"display:none\"" + " ";
			} else {
				display += String.format(DISPLAY, fieldName) + " ";
			}
			String result = String.format(FILED_FORMAT, display, fieldText, input);

			return result;
		} else if ("radio".equals(field.getFieldType())) {

			String readonly = String.format(READONLY, fieldName);
//			String validate = "";

//			if ("Y".equals(field.getIsNecessary()))
//				validate += "required=\"true\"" + " " + String.format(MISSINGMESSAGE, fieldText) + " ";

			String defaultValue = "";
			if (field.getDefaultValue() != null && !"".equals(field.getDefaultValue()))
				defaultValue = field.getDefaultValue();

			String input = String.format(HIDDEN_FORMAT, fieldName, fieldName, defaultValue);
			List<Option> options = sysParamService.getOptions(field.getFieldOption(), FieldTypeDefin.getFiledTypeByKey(field.getFieldType()).getParam());
			for (Option option : options) {
				input += String.format(RADIO_FORMAT, readonly, fieldName, option.getId(), option.getName());
			}
			String display = "";
			if (field.getIsShow() != null && "N".equals(field.getIsShow())) {
				display += "style=\"display:none\"" + " ";
			} else {
				display += String.format(DISPLAY, fieldName) + " ";
			}

			String result = String.format(FILED_FORMAT, display, fieldText, input);

			return result;
		} else if ("checkbox".equals(field.getFieldType())) {
			String readonly = String.format(READONLY, fieldName);
			String validate = "";

			if ("Y".equals(field.getIsNecessary()))
//				validate += "required=\"true\"" + " " + String.format(MISSINGMESSAGE, fieldText) + " ";
				validate += "required=\"true\"" + " ";

			String defaultValue = "";
			if (field.getDefaultValue() != null && !"".equals(field.getDefaultValue()))
				defaultValue = field.getDefaultValue();

			String input = String.format(HIDDEN_FORMAT, fieldName, fieldName, defaultValue);
			List<Option> options = sysParamService.getOptions(field.getFieldOption(), FieldTypeDefin.getFiledTypeByKey(field.getFieldType()).getParam());
			for (Option option : options) {
				input += String.format(CHECKBOX_FORMAT, readonly, validate, fieldName, option.getId(), option.getName());
			}

			String display = "";
			if (field.getIsShow() != null && "N".equals(field.getIsShow())) {
				display += "style=\"display:none\"" + " ";
			} else {
				display += String.format(DISPLAY, fieldName) + " ";
			}
			String result = String.format(FILED_FORMAT, display, fieldText, input);

			return result;
		} else if ("select".equals(field.getFieldType())) {
			String readonly = String.format(READONLY, fieldName);
//			String validate = "";

//			if ("Y".equals(field.getIsNecessary()))
//				validate += "required=\"true\"" + " " + String.format(MISSINGMESSAGE, fieldText) + " ";

			String defaultValue = "";
			if (field.getDefaultValue() != null && !"".equals(field.getDefaultValue()))
				defaultValue = field.getDefaultValue();
			String input = String.format(HIDDEN_FORMAT, fieldName, fieldName, defaultValue);
			List<Option> options = sysParamService.getOptions(field.getFieldOption(), FieldTypeDefin.getFiledTypeByKey(field.getFieldType()).getParam());
			String ops = "";
			for (Option option : options) {
				ops += String.format(OPTION_FORMAT, option.getId(), option.getName());
			}
			input += String.format(SELECT_FORMAT, readonly, fieldName, ops);

			String display = "";
			if (field.getIsShow() != null && "N".equals(field.getIsShow())) {
				display += "style=\"display:none\"" + " ";
			} else {
				display += String.format(DISPLAY, fieldName) + " ";
			}
			String result = String.format(FILED_FORMAT, display, fieldText, input);

			return result;
		} else if ("tree".equals(field.getFieldType())) {
			String readonly = String.format(READONLY, fieldName);
			String validate = "";

			if ("Y".equals(field.getIsNecessary()))
//				validate += "required=\"true\"" + " " + String.format(MISSINGMESSAGE, fieldText) + " ";
				validate += "required=\"true\"" + " ";

			String defaultValue = "";
			if (field.getDefaultValue() != null && !"".equals(field.getDefaultValue()))
				defaultValue = field.getDefaultValue();

			List<Option> options = sysParamService.getOptions(field.getFieldOption(), FieldTypeDefin.getFiledTypeByKey(field.getFieldType()).getParam());

			String temPath = AppContext.getProperties("treeUrlpath");
			String url = temPath + "/" + TreeUtils.getJsonFile(options, field.getFieldOption(), "").getName();// TODO
																												// 调整路径

			String input = String.format(TREE_FORMAT, readonly, validate, url, fieldName, fieldName, defaultValue);

			String display = "";
			if (field.getIsShow() != null && "N".equals(field.getIsShow())) {
				display += "style=\"display:none\"" + " ";
			} else {
				display += String.format(DISPLAY, fieldName) + " ";
			}
			String result = String.format(FILED_FORMAT, display, fieldText, input);

			return result;

		} else if ("richTextEditer".equals(field.getFieldType())) {
			String readonly = String.format(READONLY, fieldName);
			String validate = "";

			if ("Y".equals(field.getIsNecessary()))
//				validate += "required=\"true\"" + " " + String.format(MISSINGMESSAGE, fieldText) + " ";
				validate += "required=\"true\"" + " ";

			if (field.getFieldLength() != null) {
//				String validatType = "length[0," + field.getFieldLength().intValue() + "]";
//				String invalidMessage = "长度不能大于" + field.getFieldLength().intValue() + "！";
//				validate += String.format(VALIDATTYPE, validatType) + " ";
//				validate += String.format(INVALIDMESSAGE, invalidMessage) + " ";
				validate += "maxlength=\"" + field.getFieldLength().intValue() + "\"";
			}
			validate += "style=\"width:711px;height:100px;display:none\"";
			String defaultValue = "";
			if (field.getDefaultValue() != null && !"".equals(field.getDefaultValue()))
				defaultValue = field.getDefaultValue();

			String input = String.format(RICHTEXT_FORMAT, readonly, validate, fieldName, fieldName, defaultValue);

			String display = "";
			if (field.getIsShow() != null && "N".equals(field.getIsShow())) {
				display += "style=\"display:none\"" + " ";
			} else {
				display += String.format(DISPLAY, fieldName) + " ";
			}
			String result = String.format(FILED_FORMAT, display, fieldText, input);

			return result;
		} else if ("systemVar".equals(field.getFieldType())) {
//			String validate = "style=\"width:284px;height:25px;border:0;background:transparent;\"" + " ";
			String input = "";
			List<Option> options = sysParamService.getOptions(field.getFieldOption(), FieldTypeDefin.getFiledTypeByKey(field.getFieldType()).getParam());
			// --一般options的size 为1 optionName 和optionValue 可能相同
			// 例如当前用户这个系统变量，optionName和optionValue可以都为表达式
			for (Option option : options) {
				input += String.format(SYSVAR_FORMAT, fieldName, fieldName, "${" + option.getValue() + "}");
			}

			String display = "";
			if (field.getIsShow() != null && "N".equals(field.getIsShow())) {
				display += "style=\"display:none\"" + " ";
			} else {
				display += String.format(DISPLAY, fieldName) + " ";
			}
			String result = String.format(FILED_FORMAT, display, fieldText, input);

			return result;

		} else if ("url".equals(field.getFieldType())) {

//			String clazz = "easyui-validatebox" + " ";
			String clazz = String.format(READONLY, fieldName) + " ";

			String validate = "url=\"true\"" + " ";
//			validate += String.format(VALIDATTYPE, "url") + " ";
			if ("Y".equals(field.getIsNecessary()))
//				validate += "required=\"true\"" + " " + String.format(MISSINGMESSAGE, fieldText) + " ";
				validate += "required=\"true\"" + " ";

			String defaultValue = "";
			if (field.getDefaultValue() != null && !"".equals(field.getDefaultValue()))
				defaultValue = field.getDefaultValue();

			String input = String.format(TEXT_FORMAT, clazz, validate, fieldName, fieldName, defaultValue);

			String display = "";
			if (field.getIsShow() != null && "N".equals(field.getIsShow())) {
				display += "style=\"display:none\"" + " ";
			} else {
				display += String.format(DISPLAY, fieldName) + " ";
			}
			String result = String.format(FILED_FORMAT, display, fieldText, input);

			return result;
		}
		return null;
	}

	// --合并模板 by --zili
	public static String mergeTemplate(String formHtml) {
		HttpServletRequest request = (HttpServletRequest) ThreadLocalContext.get(Constants.CONTEXT_HTTPREQ);
		String contextPath = "";
		if (request != null) {
			try {
				// fengjinshou 20151217
				contextPath = request.getSession().getServletContext().getRealPath("/");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		String temPath = contextPath + java.io.File.separator + AppContext.getProperties("formTemplatePath");
		File folder = new File(temPath);
		File temp = new File(folder, "form.template");
		if (!temp.exists())
			return "系统模板不存在！";
		String tempString = "";
		try {
			// 清空jsoup的转义表，会使jsoup失去转义能力
			Entities.EscapeMode.base.getMap().clear();
			org.jsoup.nodes.Document doc = Jsoup.parse(temp, "UTF-8", "");
			org.jsoup.nodes.Element div = doc.getElementById("form-Tem");
			div.append(formHtml);
			tempString = doc.html();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return FreeMakerUtils.unescapeFreemarkerToHtmlForJsoup(tempString);
	}

	/**
	 * @Description : 合并模板
	 * @param templatePath
	 *            模板路径，相对路径（应用根目录）
	 * @param htmlPaths
	 *            html片段路径（相对于应用根目录），按照可变参数的前后顺序插入到模板中
	 * @return
	 * @return : String
	 * @version : v1.00
	 */
	public static String mergeTemplate(String templatePath, String... htmlPaths) {
		HttpServletRequest request = (HttpServletRequest) ThreadLocalContext.get(Constants.CONTEXT_HTTPREQ);
		String contextPath = "";
		if (request != null) {
			try {
				// fengjinshou 20151217
				contextPath = request.getSession().getServletContext().getRealPath("/");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		String temPath = contextPath + File.separator + templatePath;
		File temp = new File(temPath);
		if (!temp.exists())
			return "系统模板不存在！";
		String tempString = "";
		try {
			// 清空jsoup的转义表，会使jsoup失去转义能力
			Entities.EscapeMode.base.getMap().clear();
			Document doc = Jsoup.parse(temp, "UTF-8");
			Element div = doc.getElementById("form-Tem");
			File htmlFile = null;
			for (String htmlPath : htmlPaths) {
				htmlFile = new File(contextPath + File.separator + htmlPath);
				if (htmlFile.exists()) {
					Document htmlDoc = Jsoup.parse(htmlFile, "UTF-8");
					String htmlSource = htmlDoc.html();
					div.append(htmlSource);
				} else {
					return "表单模板或者意见模板不存在!";
				}
			}
			tempString = doc.html();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return FreeMakerUtils.unescapeFreemarkerToHtmlForJsoup(tempString);
	}

	/**
	 * 通过表单模板转化成表单预览模板
	 */
	public static String getViewHtmlByTemplate(String template) {
		// 清空jsoup的转义表，会使jsoup失去转义能力
		Entities.EscapeMode.base.getMap().clear();
		Document doc = Jsoup.parse(template, "UTF-8");
		Elements handles = doc.getElementsByClass("handle");
		Elements handle = handles.get(0).children();
		String closeHtml = "";
		for (int i = 0; i < handle.size(); i++) {
			Element a = handle.get(i);
			if (a.hasClass("icon_close")) {
				closeHtml = a.toString();
			}
		}
		handles.html("<a href='javascript:void(0);' class='icon_print' onclick = 'printPage()'>打印</a>" + closeHtml);
		Elements divs = doc.getElementsByClass("item-data");
		for (int i = 0; i < divs.size(); i++) {
			Element div = divs.get(i);
			Elements inputs = div.children();
			if (inputs.size() == 1) {
				Element input = inputs.get(0);
				if (input.hasClass("easyui-combotree ")) {
					// --tree
					String value = input.attr("value");
					div.html(value.replaceAll("value", "text"));
				} else if (input.tagName().equals("textarea")) {
					String value = input.text();// 原来的方法对于长标题会造成显示不全，界面变乱zhangyong
												// 20140722
					// fengjinshou 20160421
					div.attr("style", "height:auto;width:733px;max-width:733px;");
					div.html("<div style=\"width:733px;height:auto;line-height:1.5;padding:5px 5px;border:0px;white-space:normal;overflow-x:hidden;\">"
							+ value + "</div>");
					div.parent().attr("style", "height:auto;width:838px;");
					div.previousElementSibling().attr("style", "height:" + div.attr("height") + ";text-align:center");
				} else {
					String value = input.attr("value");
					div.html(value);
				}

			} else {
				for (int j = 0; j < inputs.size(); j++) {
					Element input = inputs.get(j);
					if (input.attr("type").equals("hidden") || input.attr("type").equals("button")) {
						// String value = input.attr("value");
						// div.html(value.replaceAll("value", "text"));
						input.remove();
						break;
					} else if (input.tagName().equals("textarea")) {// liujie
																	// add
																	// 20160509
						String value = input.text();
						div.attr("style", "height:auto;width:733px;max-width:733px;");
						div.parent().attr("style", "height:auto;width:838px;");
						div.previousElementSibling().attr("style", "height:auto;");
						String html = "<div style=\"width:733px;height:auto;line-height:1.5;padding:5px 5px;border:0px;white-space:normal;overflow-x:hidden;\">"
								+ value + "</div>";
						input.after(html);
						input.remove();
					} else {
						input.after(input.attr("value"));// fengjinshou 2016035
						input.remove();
					}
				}

			}

		}
		return FreeMakerUtils.unescapeFreemarkerToHtmlForJsoup(doc.html());
	}

	public static void main(String[] args) throws IOException {

		Field field = new Field();
		field.setFieldText("费用明细");
		field.setFieldName("legend");
		field.setFieldType("select");
		field.setFieldOption("1");
		TemplateCreater templateCreater = new TemplateCreater();
		String div = templateCreater.getFieldDivM(field);
		System.out.println("=============" + div);
	}

	/**
	 *
	 * 建立日期 : Aug 21, 2013 11:33:30 AM<br>
	 * 作者: 孙耀飞<br>
	 * 模块: <br>
	 * 描述: 创建客户端表单模板<br>
	 * 1 <br>
	 * 2 <br>
	 */
	public static String createMobileTemplate(Form form) {
		List<Field> fields = new ArrayList<Field>();
		FieldService fieldManager = (FieldService) BeanFactory.getBean("fieldService");
		fields = fieldManager.getShowFieldsByformId(form.getFormId());
		String fieldDivs = "";
		for (Field field : fields) {
			String fieldDiv = getFieldDivM(field);
			fieldDivs += fieldDiv;
		}
		/*
		 * String contextPath =
		 * ServletActionContext.getServletContext().getRealPath
		 * (java.io.File.separator); if(StringUtils.isBlank(contextPath)){
		 * contextPath =
		 * ServletActionContext.getServletContext().getRealPath("/"); } String
		 * temPath = contextPath+
		 * java.io.File.separator+AppContext.getProperties
		 * ("mobileFormTemplatePath"); File folder = new File(temPath); File
		 * temp = new File(folder,"form.template"); if(!temp.exists()) return
		 * "系统模板不存在！"; String tempString = ""; try { Document doc =
		 * Jsoup.parse(temp, "UTF-8", ""); Element div =
		 * doc.getElementById("dataForm"); div.append(fieldDivs); tempString =
		 * doc.html(); } catch (IOException e) { e.printStackTrace(); }
		 */
		return fieldDivs;
	}

	public static String getDefaultTemplateDirectory(){
	  HttpServletRequest request = (HttpServletRequest) ThreadLocalContext.get(Constants.CONTEXT_HTTPREQ);
      String contextPath = "";
      if (request != null) {
          try {
              // fengjinshou 20151217
              contextPath = request.getSession().getServletContext().getRealPath("/");
          } catch (Exception e) {
              e.printStackTrace();
          }
      }

      String temPath = contextPath + java.io.File.separator + AppContext.getProperties("formTemplatePath");
      return temPath;
	}


	/**
	 * @Description : 合并客户端模板
	 * @param templatePath
	 *            模板路径
	 * @param formPath
	 *            表单路径
	 * @param opinionPath
	 *            意见路径
	 * @return
	 * @return : String
	 * @version : v1.00
	 */
	public static String mergeMobileTemplate(String templatePath, String formPath, String opinionPath) {
		HttpServletRequest request = (HttpServletRequest) ThreadLocalContext.get(Constants.CONTEXT_HTTPREQ);
		String contextPath = "";
		if (request != null) {
			try {
				// fengjinshou 20151217
				contextPath = request.getSession().getServletContext().getRealPath("/");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		String temPath = contextPath + File.separator + templatePath;
		File temp = new File(temPath);
		if (!temp.exists())
			return "客户端系统模板不存在！";
		String tempString = "";
		try {
			// 清空jsoup的转义表，会使jsoup失去转义能力
			Entities.EscapeMode.base.getMap().clear();
			Document doc = Jsoup.parse(temp, "UTF-8");

			// 把表单片段插入模板
			if (StringUtils.isNotBlank(formPath)) {
				Element formDiv = doc.getElementById("dataForm");
				File formFile = new File(contextPath + File.separator + formPath);
				if (formFile.exists()) {
					Document formDoc = Jsoup.parse(formFile, "UTF-8");
					String formSource = formDoc.html();
					formDiv.append(formSource);
				} else {
					return "客户端表单html文件不存在！";
				}
			}

			// 把意见片段插入模板
			if (StringUtils.isNotBlank(opinionPath)) {
				Element opinionDiv = doc.getElementById("content2");
				File opinionFile = new File(contextPath + File.separator + opinionPath);
				if (opinionFile.exists()) {
					Document opinionDoc = Jsoup.parse(opinionFile, "UTF-8");
					String opinionSource = opinionDoc.html();
					opinionDiv.append(opinionSource);
				} else {
					return "客户端意见html文件不存在！";
				}
			}
			tempString = doc.html();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return FreeMakerUtils.unescapeFreemarkerToHtmlForJsoup(tempString);
	}

	/**
	 * @Description : 合并客户端模板
	 * @param templatePath
	 *            模板路径
	 * @param htmlSources
	 *            片段字符串
	 * @return
	 * @return : String
	 * @version : v1.00
	 */
	public static String mergeMobileTemplateWithHtmlSource(String templatePath, String... htmlSources) {
		HttpServletRequest request = (HttpServletRequest) ThreadLocalContext.get(Constants.CONTEXT_HTTPREQ);
		String contextPath = "";
		if (request != null) {
			try {
				// fengjinshou 20151217
				contextPath = request.getSession().getServletContext().getRealPath("/");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		String temPath = contextPath + File.separator + templatePath;
		File temp = new File(temPath);
		if (!temp.exists())
			return "客户端系统模板不存在！";
		String tempString = "";
		try {
			// 清空jsoup的转义表，会使jsoup失去转义能力
			Entities.EscapeMode.base.getMap().clear();
			Document doc = Jsoup.parse(temp, "UTF-8");
			Element div = doc.getElementById("dataForm");
			for (String htmlSource : htmlSources) {
				if (StringUtils.isNotBlank(htmlSource)) {
					div.append(htmlSource);
				} else {
					return "客户端表单模板或者意见模板不存在!";
				}
			}
			tempString = doc.html();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return FreeMakerUtils.unescapeFreemarkerToHtmlForJsoup(tempString);
	}


	/**
	 * 生成意见代码片段
	 * @author balancejia
	 * @date 2016-12-13
	 * @param appId
	 * @return
	 */
	public static String opnTml(String appId){
		String tml="<tr class=\"opinion-area\" activity=\"%s\"><th class=\"opinion-title\">%s</th><td class=\"opinion-list\"></td></tr>";
		CommentService cService=(CommentService)BeanFactory.getBean("commentService");
		List<Activity> acts = cService.getOpnAct(appId);
		String html="";
		for(Activity act:acts){
			String actName=act.getActivityName();
			html+=String.format(tml, actName,actName);
		}
		return html;
	}

}